using Microsoft.EntityFrameworkCore;
using TerritoryGame.Domain.Entities;
using TerritoryGame.Domain.Repositories;
using TerritoryGame.Domain.ValueObjects;
using TerritoryGame.Infrastructure.Data;

namespace TerritoryGame.Infrastructure.Repositories;

public class GameRepository : IGameRepository
{
    private readonly TerritoryGameDbContext _context;

    public GameRepository(TerritoryGameDbContext context)
    {
        _context = context;
    }

    public async Task<Game?> GetByIdAsync(GameId id)
    {
        return await _context.Games
            .Include(g => g.Players)
            .Include(g => g.Canvas)
            .FirstOrDefaultAsync(g => g.Id == id);
    }

    public async Task<Game?> GetByRoomCodeAsync(string roomCode)
    {
        // 这里需要根据房间代码生成逻辑来查找游戏
        // 暂时使用简单的实现，实际应该根据房间代码生成算法来查找
        return await _context.Games
            .Include(g => g.Players)
            .Include(g => g.Canvas)
            .FirstOrDefaultAsync(g => g.Name.Value.Contains(roomCode));
    }

    public async Task<IEnumerable<Game>> GetAllAsync()
    {
        return await _context.Games
            .Include(g => g.Players)
            .Include(g => g.Canvas)
            .ToListAsync();
    }

    public async Task<Game> AddAsync(Game game)
    {
        _context.Games.Add(game);
        await _context.SaveChangesAsync();
        return game;
    }

    public async Task<Game> UpdateAsync(Game game)
    {
        _context.Games.Update(game);
        await _context.SaveChangesAsync();
        return game;
    }

    public async Task DeleteAsync(GameId id)
    {
        var game = await GetByIdAsync(id);
        if (game != null)
        {
            _context.Games.Remove(game);
            await _context.SaveChangesAsync();
        }
    }

    public async Task<bool> ExistsAsync(GameId id)
    {
        return await _context.Games.AnyAsync(g => g.Id == id);
    }

    public async Task<bool> ExistsByRoomCodeAsync(string roomCode)
    {
        return await _context.Games.AnyAsync(g => g.Name.Value.Contains(roomCode));
    }
}
